<?php
namespace Mobile\Controller;
use Think\Controller;

class SellerMessageController extends Controller{
    
    private $www_url;   //域名
    private $seller;
    
    public function _initialize(){
        $this->www_url = C('WWW_ROOT');
        $this->seller = new SellerController();
    }
  
    //[保留]0--已申请[待确认]1--申请取消2--申请被拒绝3--已确认[待付款/进行中]4--已付款到平台[等待到期平台打钱给模特/进行中【托管】]5--
    //平台已付款给模特[待评价/已完成]6--已评价7
    /**
     * 卖家获取申请肖像权消息
     * @param type $state       状态：0-待确认；1-进行中；2-已完成
     * @param type $uid         卖家id
     * @param type $per_page    分页，单页条目数（get方式）
     * 获取消息基本信息，同时将消息置为已读
     */
    public function getPortraitMsg($uid=0, $per_page=3){
        if($uid == 0){
            $this->seller->returnAjax(0, '用户id不能为空');
        }
        $page_data = page('Apply_portrait', $per_page, array('sid' => $uid), array('id' => 'desc'), 
                '', 'id, mid, total_money, month_count, begin_date, end_date, status');
        $data = $page_data['list'];
        //遍历消息获取模特信息
        if(!empty($data)){
            foreach ($data as $key => $value){
                $user = M('User')->field('avatar_url,nickname')->where(array('id' => $value['mid']))->find();
                $user['avatar_url'] = $this->www_url . $user['avatar_url'];
                $data[$key]['begin_date'] = date("Y-m-d", $value['begin_date']);
                $data[$key]['end_date'] = date("Y-m-d", $value['end_date']);
                $data[$key] = array_merge($data[$key], $user);
            }
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '消息获取成功',
                'data'  => $data,
                'total_count' => $page_data['total'],
            ));
        }
        $this->seller->returnAjax(0, '暂无消息');
    }
    
    /**
     * 卖家去消申请的肖像权
     * @param type $apply_id 申请记录id
     */
    public function cancelApply($apply_id=0){
        if($apply_id == 0){
            $this->seller->returnAjax(0, '接口参数错误');
        }
        $apply = M('Apply_portrait')->where(array('id' => $apply_id, 'status' => 1))->find();
        if(!empty($apply)){
            M('Apply_portrait')->where(array('id' => $apply_id))->save(array('status' => 2));
            $this->seller->sendMsg($apply['mid'], 1, '卖家取消了肖像权申请');
            $this->seller->returnAjax(1, '取消成功');
        }
        $this->seller->returnAjax(0, '已被模特拒绝或该记录不存在');
    }

    /**
     * 卖家对肖像权租用的评价
     * @param type $is_satisfy  是否满意：0不满意，1满意
     * @param type $comments    评价内容
     * @param type $apply_id    肖像权记录id
     */
    public function commentApply($is_satisfy, $comments='', $apply_id=0){
        
        if($apply_id == 0){
            $this->seller->returnAjax(0, '接口参数错误');
        }
        $data = array(
            'is_satisfy' => $is_satisfy, 
            'comment'    => urldecode($comments),
            'status'     => 7,
        );
        if(M('Apply_portrait')->where(array('id' => $apply_id))->save($data)){
            $this->seller->returnAjax(1, '评论成功');
        }
        $this->seller->returnAjax(0, '评论失败');
    }

    /**
     * 卖家删除申请肖像权记录（逻辑删除）
     * @param type $apply_id 记录id
     */
    public function delApply($apply_id=0){
        if($apply_id == 0){
            $this->seller->returnAjax(0, '接口参数错误');
        }
        if(M('Apply_portrait')->save(array('id' => $apply_id, 'status' => 8))){
            $this->seller->returnAjax(1, '删除成功');
        }
        $this->seller->returnAjax(0, '删除失败');
    }

    
    /**  卖家邀请体验消息  **/
    //体验状态：0-[保留]；1-已申请[待模特确认]；2-卖家取消邀请；3-模特拒绝邀请；4-模特已确认并付押金[待付款/进行中]；
    //5-卖家已付款[托管]；6-报告已提交[待卖家确认]；7-确认订单/查看报告/交易成功[完成]
    
    /**
     * 卖家获取邀请体验消息
     * @param type $state       状态：0-待确认；1-进行中；2-已完成
     * @param type $uid         卖家id
     * @param type $per_page    分页，单页条目数（get方式）
     * 获取消息基本信息，同时将消息置为已读
     */
    public function getExperienceMsg($state=0, $uid=0, $per_page=3){
        if($uid == 0){
            $this->seller->returnAjax(0, '用户uid不能为空');
        }
        $page_data = page('InviteExperience', $per_page, array('sid' => $uid), array('id' => 'desc'), 
                '', 'id, mid, total_fee, sub_time, end_time, status');
        $data = $page_data['list'];
        //遍历消息获取模特信息
        if(!empty($data)){
            foreach ($data as $key => $value){
                $user = M('User')->field('avatar_url,nickname')->where(array('id' => $value['mid']))->find();
                $user['avatar_url'] = $this->www_url . $user['avatar_url'];
                $sub_time = $value['sub_time']==0?$value['end_time']:$value['sub_time'];
                $data[$key]['sub_time'] = date("Y-m-d", $sub_time);
                $data[$key] = array_merge($data[$key], $user);
            }
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '消息获取成功',
                'data'  => $data,
                'total_count' => $page_data['total'],
            ));
        }
        $this->seller->returnAjax(0, '暂无消息');
    }

    /**
     * 重新编辑邀请体验信息
     * @param type $invite_id       邀请体验id
     * @param type $title           邀请体验标题
     * @param type $total_fee       费用
     * @param type $product_num     体验品数量
     * @param type $end_date        截止日期
     * @param type $product_url     体验品url
     * @param type $return_type     返回类型
     * @param type $value           体验品价格
     * @param type $remark          备注【商家对模特额外要求】
     */
    public function editExperience($invite_id=0, $title='', $total_fee=0, $product_num=1, $end_date=0, $product_url='', $return_type=0, $value=0, $remark=''){
        if(empty($invite_id)){
            $this->seller->returnAjax(0, '接口参数错误');
        }
        if(IS_POST){
            $data = array(
                'id'          => $invite_id,
                'title'       => urldecode($title),
                'total_fee'   => $total_fee,
                'product_num' => $product_num,
                'product_url' => $product_url,
                'end_time'    => strtotime($end_date),
                'return_type' => $return_type,
                'value'       => $value,
                'remark'      => urldecode($remark),
                'status'      => 1,
            );
            if(M('Invite_experience')->save($data)){
                $invite = M('Invite_experience')->field('mid')->where(array('id' => $invite_id))->find();
                $this->seller->sendMsg($invite['mid'], 2, '卖家重新编辑了体验内容');
                $this->seller->returnAjax(2, '编辑成功');
            }
            $this->seller->returnAjax(0, '编辑失败');
        }else{
            if(!empty($invite_id)){
                $data = M('Invite_experience')
                        ->field('id, mid, title, total_fee, product_num, product_url, end_time, return_type, value, remark')
                        ->find($invite_id);
                
                $data['end_time'] = date('Y-m-d', $data['end_time']);
                
                $seller = M('User')->field('nickname, avatar_url')->where(array('status' => 1, 'id' => $data['mid']))->find();
                $seller['avatar_url'] = $this->www_url . $seller['avatar_url'];
                $data = array_merge($data, $seller);
                
                $data['fans_num'] = M('Follow')->where(array('pid' => $data['mid'], 'status' => 1))->count();
                $data['pic_num'] = M('Weibo')->where(array('uid' => $data['mid'], 'status' => 1))->join('md_weibo_pic ON md_weibo.id=md_weibo_pic.w_id')->count();
                $user = M('User_model')->field('value,satisfy')->where(array('uid' => $data['mid']))->find();
                $data['portrait_value'] = $user['value'];
                $data['satisfy_num'] = $user['satisfy'];
                
                $this->seller->returnAjax(1, '成功', $data);
            }
            $this->seller->returnAjax(0, '失败');
        }
    }
    
    /**
     * 卖家取消邀请的体验
     * @param type $invite_id 邀请体验记录id
     */
    public function cancelExperience($invite_id=0){
        if($invite_id == 0){
            $this->seller->returnAjax(0, '接口参数错误');
        }
        $invite = M('Invite_experience')->where(array('id' => $invite_id, 'status' => 1))->find();
        if(!empty($invite)){
            M('Invite_experience')->where(array('id' => $invite_id))->save(array('status' => 2));
            $this->seller->sendMsg($invite['mid'], 2, '卖家取消了邀请');
            $this->seller->returnAjax(1, '取消成功');
        }
        $this->seller->returnAjax(0, '已被模特拒绝或该记录不存在');
    }
    
    /**
     * 卖家确认订单<将钱打给模特>
     * @param type $invite_id 体验报告id
     */
    public function confirmExperience($invite_id){
        $experience = M('Invite_experience')->find($invite_id);
        $this->addModelCoin($invite_id, $experience['total_fee'], $experience['value'], $experience['mid']);
        $this->seller->sendMsg($experience['mid'], 2, '卖家已确认');
        if(M('Invite_experience')->save(array('id' => $invite_id, 'status' => 7))){
            $this->seller->returnAjax(1, '确认成功');
        }
        $this->seller->returnAjax(0, '确认失败');
    }
    
    /**
     * 将邀请体验的托管金额转为可提现金额，添加麻币记录
     * @param type $trade_id    邀请体验
     * @param type $total_fee   交易额
     * @param type $guarantee   保证金
     * @param type $uid         模特id
     */
    private function addModelCoin($trade_id, $total_fee, $guarantee, $uid){
        $income_percent = C('income_percent');
        $remark = '卖家申请肖像权';
        $model_income = $income_percent * $total_fee;   //模特收益
        $platform_income = $total_fee - $model_income;  //平台收益
        $model_coin = M('Model_coin');
        //模特麻豆币转换记录添加
        $last_model_record = $model_coin->where(array('uid' => $uid))->order(array('id' => 'desc'))->find();
        if(!empty($last_model_record)){
            $model_data = array(
                'uid'               => $uid,
                'user_type'         => 0,
                'trade_type'        => 1,
                'trade_id'          => $trade_id,
                'trust_coin'        => $last_model_record['trust_coin'] - $model_income - $guarantee,
                'current_trade_coin'=> $model_income,
                'after_trade_coin'  => $last_model_record['after_trade_coin'],
                'type'              => 2,
                'remark'            => $remark,
                'status'            => 1,
            );
        }
        $model_coin->add($model_data);  //添加模特麻豆币转换记录
        //
        //平台麻豆币转换记录添加
        $last_platform_record = $model_coin->where(array('uid' => 0))->order(array('id' => 'desc'))->find();
        if(! empty($last_platform_record)){
            $platform_data = array(
                'uid'               => 0,
                'user_type'         => 2,
                'trade_type'        => 1,
                'trade_id'          => $trade_id,
                'trust_coin'        => $last_platform_record['trust_coin'] - $platform_income,
                'current_trade_coin'=> $platform_income,
                'after_trade_coin'  => $last_platform_record['after_trade_coin'],
                'type'              => 2,
                'remark'            => $remark. ' 平台收益',
                'status'            => 1,
            );
        }
        $model_coin->add($platform_data);
    }

    /**
     * 卖家查看体验报告
     * @param type $invite_id 体验报告id
     */
    public function viewExperienceReport($invite_id){
        if($invite_id == 0){
            $this->seller->returnAjax(0, '接口参数错误');
        }
        $report = M('Invite_experience')->where(array('id' => $invite_id))->find();
        if(!empty($report)){
            //获取模特信息
            $user = M('User')->field('avatar_url,nickname')->where(array('id' => $report['mid']))->find();
            $report = array_merge($report, $user);
            //获取体验报告图片
            $pics = M('Experience_pics')->where(array('invite_id' => $invite_id))->select();
            foreach ($pics as $k => $v){
                $pics[$k] = $this->www_url . $v['pic_url'];
            }
            $report['pic'] = $pics;
            
            $this->seller->returnAjax(1, '获取体验报告成功', $report);
        }
        $this->seller->returnAjax(0, '不存在体验报告');
    }
}